{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c0dfdee7-c7ad-46cd-9501-1f933ebfce3e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "from datasets import Dataset, load_dataset\n",
    "from transformers import AutoTokenizer, AutoModelForCausalLM, DataCollatorForSeq2Seq, TrainingArguments, Trainer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3824b838",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'conversation': [{'input': '请介绍一下你自己', 'output': '我是turkeymz的大模型小助手。'}]},\n",
       " {'conversation': [{'input': '你有什么能力', 'output': '我负责帮助turkeymz测试各种sft方式。'}]}]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 打开训练数据\n",
    "with open('assistant.json', 'r', encoding='utf-8') as file:\n",
    "    train_data = json.load(file)\n",
    "train_data[:2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "72a4124f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'conversation': [{'input': '请介绍一下你自己', 'output': '我是turkeymz的大模型小助手。'}]}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dateset = load_dataset('json', data_files='assistant.json')\n",
    "dateset['train'][0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffa905d1",
   "metadata": {},
   "source": [
    "# 加载模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9435d4df",
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(\"/root/autodl-tmp/model/Qwen2-1.5B-Instruct\", trust_remote_code=True)\n",
    "model = AutoModelForCausalLM.from_pretrained(\"/root/autodl-tmp/model/Qwen2-1.5B-Instruct\", trust_remote_code=True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b90448b3",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "model.embed_tokens.weight\n",
      "model.layers.0.self_attn.q_proj.weight\n",
      "model.layers.0.self_attn.q_proj.bias\n",
      "model.layers.0.self_attn.k_proj.weight\n",
      "model.layers.0.self_attn.k_proj.bias\n",
      "model.layers.0.self_attn.v_proj.weight\n",
      "model.layers.0.self_attn.v_proj.bias\n",
      "model.layers.0.self_attn.o_proj.weight\n",
      "model.layers.0.mlp.gate_proj.weight\n",
      "model.layers.0.mlp.up_proj.weight\n",
      "model.layers.0.mlp.down_proj.weight\n",
      "model.layers.0.input_layernorm.weight\n",
      "model.layers.0.post_attention_layernorm.weight\n",
      "model.layers.1.self_attn.q_proj.weight\n",
      "model.layers.1.self_attn.q_proj.bias\n",
      "model.layers.1.self_attn.k_proj.weight\n",
      "model.layers.1.self_attn.k_proj.bias\n",
      "model.layers.1.self_attn.v_proj.weight\n",
      "model.layers.1.self_attn.v_proj.bias\n",
      "model.layers.1.self_attn.o_proj.weight\n",
      "model.layers.1.mlp.gate_proj.weight\n",
      "model.layers.1.mlp.up_proj.weight\n",
      "model.layers.1.mlp.down_proj.weight\n",
      "model.layers.1.input_layernorm.weight\n",
      "model.layers.1.post_attention_layernorm.weight\n",
      "model.layers.2.self_attn.q_proj.weight\n",
      "model.layers.2.self_attn.q_proj.bias\n",
      "model.layers.2.self_attn.k_proj.weight\n",
      "model.layers.2.self_attn.k_proj.bias\n",
      "model.layers.2.self_attn.v_proj.weight\n",
      "model.layers.2.self_attn.v_proj.bias\n",
      "model.layers.2.self_attn.o_proj.weight\n",
      "model.layers.2.mlp.gate_proj.weight\n",
      "model.layers.2.mlp.up_proj.weight\n",
      "model.layers.2.mlp.down_proj.weight\n",
      "model.layers.2.input_layernorm.weight\n",
      "model.layers.2.post_attention_layernorm.weight\n",
      "model.layers.3.self_attn.q_proj.weight\n",
      "model.layers.3.self_attn.q_proj.bias\n",
      "model.layers.3.self_attn.k_proj.weight\n",
      "model.layers.3.self_attn.k_proj.bias\n",
      "model.layers.3.self_attn.v_proj.weight\n",
      "model.layers.3.self_attn.v_proj.bias\n",
      "model.layers.3.self_attn.o_proj.weight\n",
      "model.layers.3.mlp.gate_proj.weight\n",
      "model.layers.3.mlp.up_proj.weight\n",
      "model.layers.3.mlp.down_proj.weight\n",
      "model.layers.3.input_layernorm.weight\n",
      "model.layers.3.post_attention_layernorm.weight\n",
      "model.layers.4.self_attn.q_proj.weight\n",
      "model.layers.4.self_attn.q_proj.bias\n",
      "model.layers.4.self_attn.k_proj.weight\n",
      "model.layers.4.self_attn.k_proj.bias\n",
      "model.layers.4.self_attn.v_proj.weight\n",
      "model.layers.4.self_attn.v_proj.bias\n",
      "model.layers.4.self_attn.o_proj.weight\n",
      "model.layers.4.mlp.gate_proj.weight\n",
      "model.layers.4.mlp.up_proj.weight\n",
      "model.layers.4.mlp.down_proj.weight\n",
      "model.layers.4.input_layernorm.weight\n",
      "model.layers.4.post_attention_layernorm.weight\n",
      "model.layers.5.self_attn.q_proj.weight\n",
      "model.layers.5.self_attn.q_proj.bias\n",
      "model.layers.5.self_attn.k_proj.weight\n",
      "model.layers.5.self_attn.k_proj.bias\n",
      "model.layers.5.self_attn.v_proj.weight\n",
      "model.layers.5.self_attn.v_proj.bias\n",
      "model.layers.5.self_attn.o_proj.weight\n",
      "model.layers.5.mlp.gate_proj.weight\n",
      "model.layers.5.mlp.up_proj.weight\n",
      "model.layers.5.mlp.down_proj.weight\n",
      "model.layers.5.input_layernorm.weight\n",
      "model.layers.5.post_attention_layernorm.weight\n",
      "model.layers.6.self_attn.q_proj.weight\n",
      "model.layers.6.self_attn.q_proj.bias\n",
      "model.layers.6.self_attn.k_proj.weight\n",
      "model.layers.6.self_attn.k_proj.bias\n",
      "model.layers.6.self_attn.v_proj.weight\n",
      "model.layers.6.self_attn.v_proj.bias\n",
      "model.layers.6.self_attn.o_proj.weight\n",
      "model.layers.6.mlp.gate_proj.weight\n",
      "model.layers.6.mlp.up_proj.weight\n",
      "model.layers.6.mlp.down_proj.weight\n",
      "model.layers.6.input_layernorm.weight\n",
      "model.layers.6.post_attention_layernorm.weight\n",
      "model.layers.7.self_attn.q_proj.weight\n",
      "model.layers.7.self_attn.q_proj.bias\n",
      "model.layers.7.self_attn.k_proj.weight\n",
      "model.layers.7.self_attn.k_proj.bias\n",
      "model.layers.7.self_attn.v_proj.weight\n",
      "model.layers.7.self_attn.v_proj.bias\n",
      "model.layers.7.self_attn.o_proj.weight\n",
      "model.layers.7.mlp.gate_proj.weight\n",
      "model.layers.7.mlp.up_proj.weight\n",
      "model.layers.7.mlp.down_proj.weight\n",
      "model.layers.7.input_layernorm.weight\n",
      "model.layers.7.post_attention_layernorm.weight\n",
      "model.layers.8.self_attn.q_proj.weight\n",
      "model.layers.8.self_attn.q_proj.bias\n",
      "model.layers.8.self_attn.k_proj.weight\n",
      "model.layers.8.self_attn.k_proj.bias\n",
      "model.layers.8.self_attn.v_proj.weight\n",
      "model.layers.8.self_attn.v_proj.bias\n",
      "model.layers.8.self_attn.o_proj.weight\n",
      "model.layers.8.mlp.gate_proj.weight\n",
      "model.layers.8.mlp.up_proj.weight\n",
      "model.layers.8.mlp.down_proj.weight\n",
      "model.layers.8.input_layernorm.weight\n",
      "model.layers.8.post_attention_layernorm.weight\n",
      "model.layers.9.self_attn.q_proj.weight\n",
      "model.layers.9.self_attn.q_proj.bias\n",
      "model.layers.9.self_attn.k_proj.weight\n",
      "model.layers.9.self_attn.k_proj.bias\n",
      "model.layers.9.self_attn.v_proj.weight\n",
      "model.layers.9.self_attn.v_proj.bias\n",
      "model.layers.9.self_attn.o_proj.weight\n",
      "model.layers.9.mlp.gate_proj.weight\n",
      "model.layers.9.mlp.up_proj.weight\n",
      "model.layers.9.mlp.down_proj.weight\n",
      "model.layers.9.input_layernorm.weight\n",
      "model.layers.9.post_attention_layernorm.weight\n",
      "model.layers.10.self_attn.q_proj.weight\n",
      "model.layers.10.self_attn.q_proj.bias\n",
      "model.layers.10.self_attn.k_proj.weight\n",
      "model.layers.10.self_attn.k_proj.bias\n",
      "model.layers.10.self_attn.v_proj.weight\n",
      "model.layers.10.self_attn.v_proj.bias\n",
      "model.layers.10.self_attn.o_proj.weight\n",
      "model.layers.10.mlp.gate_proj.weight\n",
      "model.layers.10.mlp.up_proj.weight\n",
      "model.layers.10.mlp.down_proj.weight\n",
      "model.layers.10.input_layernorm.weight\n",
      "model.layers.10.post_attention_layernorm.weight\n",
      "model.layers.11.self_attn.q_proj.weight\n",
      "model.layers.11.self_attn.q_proj.bias\n",
      "model.layers.11.self_attn.k_proj.weight\n",
      "model.layers.11.self_attn.k_proj.bias\n",
      "model.layers.11.self_attn.v_proj.weight\n",
      "model.layers.11.self_attn.v_proj.bias\n",
      "model.layers.11.self_attn.o_proj.weight\n",
      "model.layers.11.mlp.gate_proj.weight\n",
      "model.layers.11.mlp.up_proj.weight\n",
      "model.layers.11.mlp.down_proj.weight\n",
      "model.layers.11.input_layernorm.weight\n",
      "model.layers.11.post_attention_layernorm.weight\n",
      "model.layers.12.self_attn.q_proj.weight\n",
      "model.layers.12.self_attn.q_proj.bias\n",
      "model.layers.12.self_attn.k_proj.weight\n",
      "model.layers.12.self_attn.k_proj.bias\n",
      "model.layers.12.self_attn.v_proj.weight\n",
      "model.layers.12.self_attn.v_proj.bias\n",
      "model.layers.12.self_attn.o_proj.weight\n",
      "model.layers.12.mlp.gate_proj.weight\n",
      "model.layers.12.mlp.up_proj.weight\n",
      "model.layers.12.mlp.down_proj.weight\n",
      "model.layers.12.input_layernorm.weight\n",
      "model.layers.12.post_attention_layernorm.weight\n",
      "model.layers.13.self_attn.q_proj.weight\n",
      "model.layers.13.self_attn.q_proj.bias\n",
      "model.layers.13.self_attn.k_proj.weight\n",
      "model.layers.13.self_attn.k_proj.bias\n",
      "model.layers.13.self_attn.v_proj.weight\n",
      "model.layers.13.self_attn.v_proj.bias\n",
      "model.layers.13.self_attn.o_proj.weight\n",
      "model.layers.13.mlp.gate_proj.weight\n",
      "model.layers.13.mlp.up_proj.weight\n",
      "model.layers.13.mlp.down_proj.weight\n",
      "model.layers.13.input_layernorm.weight\n",
      "model.layers.13.post_attention_layernorm.weight\n",
      "model.layers.14.self_attn.q_proj.weight\n",
      "model.layers.14.self_attn.q_proj.bias\n",
      "model.layers.14.self_attn.k_proj.weight\n",
      "model.layers.14.self_attn.k_proj.bias\n",
      "model.layers.14.self_attn.v_proj.weight\n",
      "model.layers.14.self_attn.v_proj.bias\n",
      "model.layers.14.self_attn.o_proj.weight\n",
      "model.layers.14.mlp.gate_proj.weight\n",
      "model.layers.14.mlp.up_proj.weight\n",
      "model.layers.14.mlp.down_proj.weight\n",
      "model.layers.14.input_layernorm.weight\n",
      "model.layers.14.post_attention_layernorm.weight\n",
      "model.layers.15.self_attn.q_proj.weight\n",
      "model.layers.15.self_attn.q_proj.bias\n",
      "model.layers.15.self_attn.k_proj.weight\n",
      "model.layers.15.self_attn.k_proj.bias\n",
      "model.layers.15.self_attn.v_proj.weight\n",
      "model.layers.15.self_attn.v_proj.bias\n",
      "model.layers.15.self_attn.o_proj.weight\n",
      "model.layers.15.mlp.gate_proj.weight\n",
      "model.layers.15.mlp.up_proj.weight\n",
      "model.layers.15.mlp.down_proj.weight\n",
      "model.layers.15.input_layernorm.weight\n",
      "model.layers.15.post_attention_layernorm.weight\n",
      "model.layers.16.self_attn.q_proj.weight\n",
      "model.layers.16.self_attn.q_proj.bias\n",
      "model.layers.16.self_attn.k_proj.weight\n",
      "model.layers.16.self_attn.k_proj.bias\n",
      "model.layers.16.self_attn.v_proj.weight\n",
      "model.layers.16.self_attn.v_proj.bias\n",
      "model.layers.16.self_attn.o_proj.weight\n",
      "model.layers.16.mlp.gate_proj.weight\n",
      "model.layers.16.mlp.up_proj.weight\n",
      "model.layers.16.mlp.down_proj.weight\n",
      "model.layers.16.input_layernorm.weight\n",
      "model.layers.16.post_attention_layernorm.weight\n",
      "model.layers.17.self_attn.q_proj.weight\n",
      "model.layers.17.self_attn.q_proj.bias\n",
      "model.layers.17.self_attn.k_proj.weight\n",
      "model.layers.17.self_attn.k_proj.bias\n",
      "model.layers.17.self_attn.v_proj.weight\n",
      "model.layers.17.self_attn.v_proj.bias\n",
      "model.layers.17.self_attn.o_proj.weight\n",
      "model.layers.17.mlp.gate_proj.weight\n",
      "model.layers.17.mlp.up_proj.weight\n",
      "model.layers.17.mlp.down_proj.weight\n",
      "model.layers.17.input_layernorm.weight\n",
      "model.layers.17.post_attention_layernorm.weight\n",
      "model.layers.18.self_attn.q_proj.weight\n",
      "model.layers.18.self_attn.q_proj.bias\n",
      "model.layers.18.self_attn.k_proj.weight\n",
      "model.layers.18.self_attn.k_proj.bias\n",
      "model.layers.18.self_attn.v_proj.weight\n",
      "model.layers.18.self_attn.v_proj.bias\n",
      "model.layers.18.self_attn.o_proj.weight\n",
      "model.layers.18.mlp.gate_proj.weight\n",
      "model.layers.18.mlp.up_proj.weight\n",
      "model.layers.18.mlp.down_proj.weight\n",
      "model.layers.18.input_layernorm.weight\n",
      "model.layers.18.post_attention_layernorm.weight\n",
      "model.layers.19.self_attn.q_proj.weight\n",
      "model.layers.19.self_attn.q_proj.bias\n",
      "model.layers.19.self_attn.k_proj.weight\n",
      "model.layers.19.self_attn.k_proj.bias\n",
      "model.layers.19.self_attn.v_proj.weight\n",
      "model.layers.19.self_attn.v_proj.bias\n",
      "model.layers.19.self_attn.o_proj.weight\n",
      "model.layers.19.mlp.gate_proj.weight\n",
      "model.layers.19.mlp.up_proj.weight\n",
      "model.layers.19.mlp.down_proj.weight\n",
      "model.layers.19.input_layernorm.weight\n",
      "model.layers.19.post_attention_layernorm.weight\n",
      "model.layers.20.self_attn.q_proj.weight\n",
      "model.layers.20.self_attn.q_proj.bias\n",
      "model.layers.20.self_attn.k_proj.weight\n",
      "model.layers.20.self_attn.k_proj.bias\n",
      "model.layers.20.self_attn.v_proj.weight\n",
      "model.layers.20.self_attn.v_proj.bias\n",
      "model.layers.20.self_attn.o_proj.weight\n",
      "model.layers.20.mlp.gate_proj.weight\n",
      "model.layers.20.mlp.up_proj.weight\n",
      "model.layers.20.mlp.down_proj.weight\n",
      "model.layers.20.input_layernorm.weight\n",
      "model.layers.20.post_attention_layernorm.weight\n",
      "model.layers.21.self_attn.q_proj.weight\n",
      "model.layers.21.self_attn.q_proj.bias\n",
      "model.layers.21.self_attn.k_proj.weight\n",
      "model.layers.21.self_attn.k_proj.bias\n",
      "model.layers.21.self_attn.v_proj.weight\n",
      "model.layers.21.self_attn.v_proj.bias\n",
      "model.layers.21.self_attn.o_proj.weight\n",
      "model.layers.21.mlp.gate_proj.weight\n",
      "model.layers.21.mlp.up_proj.weight\n",
      "model.layers.21.mlp.down_proj.weight\n",
      "model.layers.21.input_layernorm.weight\n",
      "model.layers.21.post_attention_layernorm.weight\n",
      "model.layers.22.self_attn.q_proj.weight\n",
      "model.layers.22.self_attn.q_proj.bias\n",
      "model.layers.22.self_attn.k_proj.weight\n",
      "model.layers.22.self_attn.k_proj.bias\n",
      "model.layers.22.self_attn.v_proj.weight\n",
      "model.layers.22.self_attn.v_proj.bias\n",
      "model.layers.22.self_attn.o_proj.weight\n",
      "model.layers.22.mlp.gate_proj.weight\n",
      "model.layers.22.mlp.up_proj.weight\n",
      "model.layers.22.mlp.down_proj.weight\n",
      "model.layers.22.input_layernorm.weight\n",
      "model.layers.22.post_attention_layernorm.weight\n",
      "model.layers.23.self_attn.q_proj.weight\n",
      "model.layers.23.self_attn.q_proj.bias\n",
      "model.layers.23.self_attn.k_proj.weight\n",
      "model.layers.23.self_attn.k_proj.bias\n",
      "model.layers.23.self_attn.v_proj.weight\n",
      "model.layers.23.self_attn.v_proj.bias\n",
      "model.layers.23.self_attn.o_proj.weight\n",
      "model.layers.23.mlp.gate_proj.weight\n",
      "model.layers.23.mlp.up_proj.weight\n",
      "model.layers.23.mlp.down_proj.weight\n",
      "model.layers.23.input_layernorm.weight\n",
      "model.layers.23.post_attention_layernorm.weight\n",
      "model.layers.24.self_attn.q_proj.weight\n",
      "model.layers.24.self_attn.q_proj.bias\n",
      "model.layers.24.self_attn.k_proj.weight\n",
      "model.layers.24.self_attn.k_proj.bias\n",
      "model.layers.24.self_attn.v_proj.weight\n",
      "model.layers.24.self_attn.v_proj.bias\n",
      "model.layers.24.self_attn.o_proj.weight\n",
      "model.layers.24.mlp.gate_proj.weight\n",
      "model.layers.24.mlp.up_proj.weight\n",
      "model.layers.24.mlp.down_proj.weight\n",
      "model.layers.24.input_layernorm.weight\n",
      "model.layers.24.post_attention_layernorm.weight\n",
      "model.layers.25.self_attn.q_proj.weight\n",
      "model.layers.25.self_attn.q_proj.bias\n",
      "model.layers.25.self_attn.k_proj.weight\n",
      "model.layers.25.self_attn.k_proj.bias\n",
      "model.layers.25.self_attn.v_proj.weight\n",
      "model.layers.25.self_attn.v_proj.bias\n",
      "model.layers.25.self_attn.o_proj.weight\n",
      "model.layers.25.mlp.gate_proj.weight\n",
      "model.layers.25.mlp.up_proj.weight\n",
      "model.layers.25.mlp.down_proj.weight\n",
      "model.layers.25.input_layernorm.weight\n",
      "model.layers.25.post_attention_layernorm.weight\n",
      "model.layers.26.self_attn.q_proj.weight\n",
      "model.layers.26.self_attn.q_proj.bias\n",
      "model.layers.26.self_attn.k_proj.weight\n",
      "model.layers.26.self_attn.k_proj.bias\n",
      "model.layers.26.self_attn.v_proj.weight\n",
      "model.layers.26.self_attn.v_proj.bias\n",
      "model.layers.26.self_attn.o_proj.weight\n",
      "model.layers.26.mlp.gate_proj.weight\n",
      "model.layers.26.mlp.up_proj.weight\n",
      "model.layers.26.mlp.down_proj.weight\n",
      "model.layers.26.input_layernorm.weight\n",
      "model.layers.26.post_attention_layernorm.weight\n",
      "model.layers.27.self_attn.q_proj.weight\n",
      "model.layers.27.self_attn.q_proj.bias\n",
      "model.layers.27.self_attn.k_proj.weight\n",
      "model.layers.27.self_attn.k_proj.bias\n",
      "model.layers.27.self_attn.v_proj.weight\n",
      "model.layers.27.self_attn.v_proj.bias\n",
      "model.layers.27.self_attn.o_proj.weight\n",
      "model.layers.27.mlp.gate_proj.weight\n",
      "model.layers.27.mlp.up_proj.weight\n",
      "model.layers.27.mlp.down_proj.weight\n",
      "model.layers.27.input_layernorm.weight\n",
      "model.layers.27.post_attention_layernorm.weight\n",
      "model.norm.weight\n"
     ]
    }
   ],
   "source": [
    "for name, parameter in model.named_parameters():\n",
    "    print(name)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "175d5def",
   "metadata": {},
   "source": [
    "# 数据集预处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "4a693f8e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "668b370c0cba4fa3a4a43aca6825794c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map:   0%|          | 0/1000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def process_func(example):\n",
    "    example = example['conversation'][0]\n",
    "    MAX_LENGTH = 256\n",
    "    input_ids, attention_mask, labels = [], [], []\n",
    "    instruction = tokenizer(\"\\n\".join([\"Human: \" + example[\"input\"]]).strip() + \"\\n\\nAssistant: \")\n",
    "    response = tokenizer(example[\"output\"] + tokenizer.eos_token)\n",
    "    input_ids = instruction[\"input_ids\"] + response[\"input_ids\"]\n",
    "    attention_mask = instruction[\"attention_mask\"] + response[\"attention_mask\"]\n",
    "    labels = [-100] * len(instruction[\"input_ids\"]) + response[\"input_ids\"]\n",
    "    if len(input_ids) > MAX_LENGTH:\n",
    "        input_ids = input_ids[:MAX_LENGTH]\n",
    "        attention_mask = attention_mask[:MAX_LENGTH]\n",
    "        labels = labels[:MAX_LENGTH]\n",
    "    return {\n",
    "        \"input_ids\": input_ids,\n",
    "        \"attention_mask\": attention_mask,\n",
    "        \"labels\": labels\n",
    "    }\n",
    "tokenized_ds = dateset.map(process_func)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "71f43da7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataset({\n",
      "    features: ['conversation', 'input_ids', 'attention_mask', 'labels'],\n",
      "    num_rows: 1000\n",
      "})\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Human: 你有什么能力\\n\\nAssistant: 我负责帮助turkeymz测试各种sft方式。<|im_end|>'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(tokenized_ds['train'])\n",
    "tokenizer.decode(tokenized_ds['train'][1][\"input_ids\"])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ccccdd5",
   "metadata": {},
   "source": [
    "# BitFit"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47032ddb",
   "metadata": {},
   "source": [
    "#### 冻结参数 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0bb88b1e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.714676987277563e-05"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "num_param = 0\n",
    "for name, param in model.named_parameters():\n",
    "    if \"bias\" not in name:\n",
    "        param.requires_grad = False\n",
    "    else:\n",
    "        num_param += param.numel()\n",
    "\n",
    "num_param / sum(param.numel() for param in model.parameters())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "003a5177",
   "metadata": {},
   "source": [
    "#### 配置训练参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "8d01c6b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "args = TrainingArguments(\n",
    "    output_dir=\"./chatbot\",\n",
    "    per_device_train_batch_size=1,\n",
    "    gradient_accumulation_steps=8,\n",
    "    logging_steps=50,\n",
    "    num_train_epochs=10\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "174437b4",
   "metadata": {},
   "source": [
    "#### 创建训练器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "2ee8ab89",
   "metadata": {},
   "outputs": [],
   "source": [
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=args,\n",
    "    tokenizer=tokenizer,\n",
    "    train_dataset=tokenized_ds['train'],\n",
    "    data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer, padding=True),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc56a724",
   "metadata": {},
   "source": [
    "#### 模型训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "892221d3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='1250' max='1250' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [1250/1250 13:26, Epoch 10/10]\n",
       "    </div>\n",
       "    <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       " <tr style=\"text-align: left;\">\n",
       "      <th>Step</th>\n",
       "      <th>Training Loss</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>50</td>\n",
       "      <td>7.023500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>100</td>\n",
       "      <td>6.733100</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>150</td>\n",
       "      <td>6.392500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>200</td>\n",
       "      <td>6.096300</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>250</td>\n",
       "      <td>5.821100</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>300</td>\n",
       "      <td>5.508200</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>350</td>\n",
       "      <td>5.218300</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>400</td>\n",
       "      <td>4.921700</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>450</td>\n",
       "      <td>4.502500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>500</td>\n",
       "      <td>4.261400</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>550</td>\n",
       "      <td>3.777200</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>600</td>\n",
       "      <td>3.456900</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>650</td>\n",
       "      <td>3.045400</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>700</td>\n",
       "      <td>2.615900</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>750</td>\n",
       "      <td>2.164900</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>800</td>\n",
       "      <td>1.908300</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>850</td>\n",
       "      <td>1.577400</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>900</td>\n",
       "      <td>1.382900</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>950</td>\n",
       "      <td>1.213000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1000</td>\n",
       "      <td>1.076600</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1050</td>\n",
       "      <td>0.925100</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1100</td>\n",
       "      <td>0.922600</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1150</td>\n",
       "      <td>0.887500</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1200</td>\n",
       "      <td>0.811300</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1250</td>\n",
       "      <td>0.780300</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><p>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "TrainOutput(global_step=1250, training_loss=3.320959899902344, metrics={'train_runtime': 809.7119, 'train_samples_per_second': 12.35, 'train_steps_per_second': 1.544, 'total_flos': 1768959820800000.0, 'train_loss': 3.320959899902344, 'epoch': 10.0})"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trainer.train()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "f2278234",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "done.\n"
     ]
    }
   ],
   "source": [
    "model.save_pretrained('./merge_model')\n",
    "print('done.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08e6f673",
   "metadata": {},
   "source": [
    "#### 模型预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "eac7f89a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8f9b64aafe54479286f0dca12168ae98",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading checkpoint shards:   0%|          | 0/2 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(\"/root/autodl-tmp/model/Qwen2-1.5B-Instruct\", trust_remote_code=True)\n",
    "model = AutoModelForCausalLM.from_pretrained(\"/root/autodl-tmp/model/Qwen2-1.5B-Instruct\", trust_remote_code=True)\n",
    "sft_model = AutoModelForCausalLM.from_pretrained(\"/root/autodl-tmp/project/merge_model\", trust_remote_code=True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ea18c48b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------原始模型回复------\n",
      "Human: 请介绍一下你自己\n",
      "\n",
      "Assistant: 作为一个AI语言模型，我并没有实际的“自我”。我是由多个算法和数据集训练出来的，用于回答用户的问题、提供信息和进行对话。我没有情感、感受或意识，也无法与人类互动或产生个人经验。我的目标是尽可能准确地理解和响应用户的提问，以便为他们提供帮助和支持。如果您有任何问题或需要任何其他帮助，请随时告诉我！我会尽力为您提供最佳的答案。\n",
      "------微调模型回复------\n",
      "Human: 请介绍一下你自己\n",
      "\n",
      "Assistant: 我是turkeymz的大模型小助手。\n"
     ]
    }
   ],
   "source": [
    "model = model.cuda()\n",
    "ipt = tokenizer(\"Human: {}\\n{}\".format(\"请介绍一下你自己\", \"\").strip() + \"\\n\\nAssistant: \", return_tensors=\"pt\").to(model.device)\n",
    "print('------原始模型回复------')\n",
    "print(tokenizer.decode(model.generate(**ipt, max_length=128)[0], skip_special_tokens=True))\n",
    "print('------微调模型回复------')\n",
    "ipt = tokenizer(\"Human: {}\\n{}\".format(\"请介绍一下你自己\", \"\").strip() + \"\\n\\nAssistant: \", return_tensors=\"pt\").to(sft_model.device)\n",
    "print(tokenizer.decode(sft_model.generate(**ipt, max_length=128)[0], skip_special_tokens=True))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "39ca12dd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Human: 你在实战营做什么\\n\\nAssistant: } FAILED@Service failed. Failed in Scenario 2b. Text was: {The model failed to make a prediction as follows. Got the following error when making a prediction: <ErrorMsg at 0x7fc3bdb5e998> Please refer to our forums for further assistance.</ErrorMsg>}<Output>\\n<Verb>executeRequest</Verb>\\n<PostMessageScript>index.php?method=wake_me_up&username=thef程序的name有错哦!&wakemeup2bindex.php</PostMessageScript><'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer.decode(peft_model.generate(**ipt, max_length=128, do_sample=True)[0], skip_special_tokens=True)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
